<?php
namespace app\index\controller;
use Db;

class Section extends Base
{

    //播放页
    public function play(){

        $id = input('section_id');

        if($id){

            //当前课时
            $info = Db::name('lesson_section a')->field('a.*,b.lesson_name,b.free_section,b.price,b.play_type,b.intro,b.image')
                ->leftJoin('lesson b','a.lesson_id=b.id')
                ->where(['a.id'=>$id])->find();

            if(empty($info['id'])){
                $this->error('课时不存在');
            }

            $this->assign('info',$info);

            //课程所有课时
            $section = Db::name('lesson_section')
                ->where(['lesson_id'=>$info['lesson_id'],'status'=>1])
                ->order('rank asc')->column('*','rank');

            $this->assign('section',$section);



            $is_look = true;  //是否可以观看

            //非会员 非免费章节 价格不为0
            if(($this->userInfo['level']==0 || $this->userInfo['level_validity']<time() ) && $info['price']>0){

                $is_look = false;

                //单独购买过此课程
                $is_pay = Db::name('order')
                    ->field('id')
                    ->where(['uid'=>$this->uid,'type'=>2,'other_id'=>$info['lesson_id'],'status'=>1])
                    ->find();
                if($is_pay){
                    $is_look = true;
                }
            }

            if(!$is_look && $info['rank']>$info['free_section'] ){

                $this->error('请先购买此课程',url('lesson/details',['id'=>$info['lesson_id']]));
            }
            
            $this->assign('is_look',$is_look);
            $this->assign('oss_path',config('api.oss_img_path'));

            if($info['play_type']==1){

                return $this->fetch('play_video');

            }else{

                return $this->fetch('play_audio');
            }

        }else{

            $this->error('未知课时');
        }


    }


    //记录播放
    public function recordPlay(){

        $lesson_id = input('lesson_id');

        $row = Db::name('lesson_study_record')->where(['uid'=>$this->uid,'lesson_id'=>$lesson_id])->find();

        if(!$row){

            Db::name('lesson')->where('id',$lesson_id)->setInc('study_num',1);

            $arr  = array(
                'lesson_id'=>$lesson_id,
                'uid'=>$this->uid,
                'ip' =>ip2long(request()->ip())
            );

            Db::name('lesson_study_record')->insert($arr);
        }

        return 'ok';
    }

}
